//
//  GQHSupplyController.m
//  Xanthium
//
//  Created by GuanQinghao on 14/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View
#import "GQHSupplyView.h"

#pragma mark Controller
#import "GQHSupplyController.h"
#import "GQHRegionController.h"
#import "GQHFreightTypeController.h"
#import "GQHModelController.h"
#import "GQHLengthController.h"

#import "GQHPushController.h"
#import <CoreLocation/CoreLocation.h>

#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHSupplyController () <GQHSupplyViewDelegate,UITextFieldDelegate> {
    
#pragma mark Data
    /// 发布货源信息参数
    __block NSMutableDictionary *parameters;
#pragma mark View
    /// 弹出框控制器
    UIAlertController *alertController;
    /// 自定义根视图
    GQHSupplyView *rootView;
}


/** 地理编码管理器 */
@property (nonatomic, strong) CLGeocoder *geoC;
@property (nonatomic, strong) CLLocation * fromLocation;
@property (nonatomic, strong) CLLocation * toLocation;

@end


@implementation GQHSupplyController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHSupplyView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    parameters = [NSMutableDictionary dictionary];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"发布货源";
    [self.qh_rightButton setTitle:@"确定" forState:UIControlStateNormal];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

/** 地理编码管理器 */
- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}

//计算距离
- (void)getDistance
{
    if (self.fromLocation && self.toLocation)
    {
        NSString * fromAddr = [NSString stringWithFormat:@"%f,%f", self.fromLocation.coordinate.longitude,self.fromLocation.coordinate.latitude];
        NSString * toAddr = [NSString stringWithFormat:@"%f,%f", self.toLocation.coordinate.longitude,self.toLocation.coordinate.latitude];
        
        NSString * url = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"buWaybill/1/getDistance"];
        [GQHNetHelper qh_requestGET:url parameters:@{@"startLonLat":fromAddr, @"endLonLat":toAddr} success:^(NSNumber *code, NSString *message, NSDictionary *data) {
            
            [parameters setObject:[NSString stringWithFormat:@"%@", data[@"distance"]] forKey:@"mileage"];
            [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@", data[@"distance"]] atIndex:2];
            [rootView.qh_tableView reloadData];
            NSLog(@"距离 : %@", data[@"distance"]);
        } failure:^(NSError *error) {
            
        }];
    }
    
//    CLLocationDistance distance = [self.fromLocation distanceFromLocation:self.toLocation];
//    NSNumber *mileage = [NSNumber numberWithInteger:(distance / 1000)];
//    [parameters setObject:[NSString stringWithFormat:@"%@", mileage] forKey:@"mileage"];
//    [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@", mileage] atIndex:2];
//    NSLog(@"距离 : %@", mileage);
}

#pragma mark --Delegate
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
            
        case 0: {
            
            /// 起始地
            GQHRegionController *regionController = [[GQHRegionController alloc] init];
            regionController.qh_regionBlock = ^(NSString *regionID, NSString *regionName, CLLocation *location)
            {
                
                if (regionID) {
                    
                    [parameters setObject:regionID forKey:@"origin"];
                    [rootView.qh_contentArray qh_safetySetObject:regionName atIndex:0];
                    [rootView.qh_tableView reloadData];
                    
                    self.fromLocation = location;
                }
            };
            [self.navigationController pushViewController:regionController animated:YES];
        }
            break;
        case 1: {
            
            if (![[parameters allKeys] containsObject:@"origin"])
            {
                return;
            }
            
            /// 目的地
            GQHRegionController *regionController = [[GQHRegionController alloc] init];
            regionController.qh_regionBlock = ^(NSString *regionID, NSString *regionName, CLLocation *location)
            {
                
                if (regionID) {
                    
                    [parameters setObject:regionID forKey:@"destination"];
                    [rootView.qh_contentArray qh_safetySetObject:regionName atIndex:1];
                    
                    self.toLocation = location;
                    [self getDistance];
                    [rootView.qh_tableView reloadData];
                }
            };
            [self.navigationController pushViewController:regionController animated:YES];
        }
            break;
//        case 2: {
            
//            /// 里程数
//            [self qh_alertWithTitle:@"请输入估算里程" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入估算里程";
//                textField.keyboardType = UIKeyboardTypeNumberPad;
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    NSNumber *mileage = [NSNumber numberWithInteger:[inputTextField.text integerValue]];
//                    [parameters setObject:mileage forKey:@"mileage"];
//                    [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@ km",mileage] atIndex:2];
//                    [rootView.qh_tableView reloadData];
//                }
//            } completion:nil];
//        }
//            break;
//        case 3: {
//
//            /// 货物名称
//            [self qh_alertWithTitle:@"请输入货物名称" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入货物名称";
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    [parameters setObject:inputTextField.text forKey:@"commodityName"];
//                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:3];
//                    [rootView.qh_tableView reloadData];
//                }
//            } completion:nil];
//        }
//            break;
        case 4: {
            
            /// 货物类型
            GQHFreightTypeController *freightTypeController = [[GQHFreightTypeController alloc] init];
            freightTypeController.qh_freightTypeBlock = ^(NSString *freightTypeID, NSString *freightTypeName) {
                
                if (freightTypeID) {
                    
                    [parameters setObject:freightTypeID forKey:@"goodsType"];
                    [rootView.qh_contentArray qh_safetySetObject:freightTypeName atIndex:4];
                    [rootView.qh_tableView reloadData];
                }
            };
            [self.navigationController pushViewController:freightTypeController animated:YES];
        }
            break;
//        case 5: {
//
//            /// 货物重量
//            [self qh_alertWithTitle:@"请输入货物重量" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入货物重量";
//                textField.keyboardType = UIKeyboardTypeNumberPad;
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    NSNumber *demandVehicle = [NSNumber numberWithInteger:[inputTextField.text integerValue]];
//                    [parameters setObject:demandVehicle forKey:@"demandVehicle"];
//                    [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@ 吨",demandVehicle] atIndex:5];
//                    [rootView.qh_tableView reloadData];
//                }
//            } completion:nil];
//        }
//            break;
//        case 6: {
//
//            /// 货物体积
//            [self qh_alertWithTitle:@"请输入货物体积" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入货物体积";
//                textField.keyboardType = UIKeyboardTypeNumberPad;
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    NSNumber *goodsVolume = [NSNumber numberWithInteger:[inputTextField.text integerValue]];
//                    [parameters setObject:goodsVolume forKey:@"goodsVolume"];
//                    [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@ 立方",goodsVolume] atIndex:6];
//                    [rootView.qh_tableView reloadData];
//                }
//            } completion:nil];
//        }
//            break;
//        case 7: {
//
//            /// 货物数量
//            [self qh_alertWithTitle:@"请输入货物数量" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入货物数量";
//                textField.keyboardType = UIKeyboardTypeNumberPad;
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    NSNumber *goodsNum = [NSNumber numberWithInteger:[inputTextField.text integerValue]];
//                    [parameters setObject:goodsNum forKey:@"goodsNum"];
//                    [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%@ 件",goodsNum] atIndex:7];
//                    [rootView.qh_tableView reloadData];
//                }
//            } completion:nil];
//        }
//            break;
//        case 8: {
//
//            /// 货物单价
//            [self qh_alertWithTitle:@"请输入货物单价" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入货物单价";
//                textField.keyboardType = UIKeyboardTypeDecimalPad;
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    if ([inputTextField.text qh_isValidDecimal] || [inputTextField.text qh_isOnlyNumber]) {
//
//                        NSNumber *freightUnitPrice = [NSNumber numberWithInteger:[inputTextField.text doubleValue]];
//                        [parameters setObject:freightUnitPrice forKey:@"freightUnitPrice"];
//                        [rootView.qh_contentArray qh_safetySetObject:[NSString stringWithFormat:@"%.2f 元/吨",[inputTextField.text doubleValue]] atIndex:8];
//                        [rootView.qh_tableView reloadData];
//                    }
//                }
//            } completion:nil];
//        }
//            break;
        case 9: {
            
            /// 需求车型
            GQHModelController *modelController = [[GQHModelController alloc] init];
            modelController.qh_modelBlock = ^(NSString *modelID, NSString *modelName) {
                
                if (modelID) {
                    
                    [parameters setObject:modelID forKey:@"demandModels"];
                    [rootView.qh_contentArray qh_safetySetObject:modelName atIndex:9];
                    [rootView.qh_tableView reloadData];
                }
            };
            [self.navigationController pushViewController:modelController animated:YES];
        }
            break;
        case 10: {
            
            /// 需求车长
            GQHLengthController *lengthController = [[GQHLengthController alloc] init];
            lengthController.qh_lengthBlock = ^(NSString *lengthID, NSString *lengthName) {
                
                if (lengthID) {
                    
                    [parameters setObject:lengthID forKey:@"demandVehicleLength"];
                    [rootView.qh_contentArray qh_safetySetObject:lengthName atIndex:10];
                    [rootView.qh_tableView reloadData];
                }
            };
            [self.navigationController pushViewController:lengthController animated:YES];
        }
            break;
        case 11: {
            
            /// 装车时间
            UIDatePicker *datePicker = [[UIDatePicker alloc] init];
            datePicker.datePickerMode = UIDatePickerModeDateAndTime;
            [datePicker addTarget:self action:@selector(datePickerChangeValue:) forControlEvents:UIControlEventValueChanged];
            
            __weak typeof(datePicker) weakDatePicker = datePicker;
            
            alertController = [UIAlertController alertControllerWithTitle:@"请选择装车时间" message: nil preferredStyle:UIAlertControllerStyleAlert];
            [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                
                textField.placeholder = @"请选择装车时间";
                textField.tag = 1011;
                textField.inputView = weakDatePicker;
            }];
            
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                UITextField *inputTextField = alertController.textFields.firstObject;
                if (inputTextField.text.length > 0) {
                    
                    [parameters setObject:inputTextField.text forKey:@"loadingTime"];
                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:11];
                    [rootView.qh_tableView reloadData];
                }
            }]];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
            break;
//        case 12: {
//
//            /// 备注
//            [self qh_alertWithTitle:@"请输入备注" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                textField.placeholder = @"请输入备注";
//            } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                UITextField *inputTextField = alertController.textFields.firstObject;
//                if (inputTextField.text.length > 0) {
//
//                    [parameters setObject:inputTextField.text forKey:@"note"];
//                    [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:12];
//                    [rootView.qh_tableView reloadData];
//                }
//            } completion:nil];
//        }
//            break;
        default:
            break;
    }
}

#pragma mark --TargetMethod
- (void)qh_clickedRightButton:(UIButton *)sender {
    
    NSArray * rowsArray = @[@"2", @"3", @"5", @"6", @"7", @"8", @"12"];
    NSArray * keysArray = @[@"mileage",
                            @"commodityName",
                            @"demandVehicle",
                            @"goodsVolume",
                            @"goodsNum",
                            @"freightUnitPrice",
                            @"note"];
    int index = 0;
    for (NSString * row in rowsArray)
    {
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row.integerValue inSection:0];
        YYEnterTextCell * cell = [rootView.qh_tableView cellForRowAtIndexPath:indexPath];
        if (row.intValue == 2)
        {
            [parameters setObject:cell.showValueLabel.text forKey:keysArray[index]];
        }
        else
        {
            [parameters setObject:cell.enterText.text forKey:keysArray[index]];
        }
        index ++;
    }
    [parameters setObject:USER_GET_ID forKey:@"releasePeople"];
    
    if (![parameters objectForKey:@"origin"]) {
        
        [self showToastWithText:@"请选择起始地"];
        return;
    }
    
    if (![parameters objectForKey:@"destination"]) {
        
        [self showToastWithText:@"请选择目的地"];
        return;
    }
    
    if (![parameters objectForKey:@"mileage"]) {
        
        [self showToastWithText:@"请输入估算里程"];
        return;
    }
    
    if ([[parameters objectForKey:@"commodityName"] length] == 0) {
        
        [self showToastWithText:@"请输入货物名称"];
        return;
    }
    
    if ([[parameters objectForKey:@"goodsType"] length] == 0) {
        
        [self showToastWithText:@"请选择货物类型"];
        return;
    }
    
    if ([[parameters objectForKey:@"demandVehicle"] length] == 0) {
        
        [self showToastWithText:@"请输入货物重量"];
        return;
    }
    
    if (0 == [[parameters objectForKey:@"demandVehicle"] integerValue]) {
        
        [self showToastWithText:@"货物重量不能为0"];
        return;
    }
    
//    if (![parameters objectForKey:@"goodsVolume"]) {
//        
//        [self showToastWithText:@"请输入货物体积"];
//        return;
//    }
//    
//    if (0 == [[parameters objectForKey:@"goodsVolume"] integerValue]) {
//        
//        [self showToastWithText:@"货物体积不能为0"];
//        return;
//    }
//    
//    if (![parameters objectForKey:@"goodsNum"]) {
//        
//        [self showToastWithText:@"请输入货物数量"];
//        return;
//    }
//    
//    if (0 == [[parameters objectForKey:@"goodsNum"] integerValue]) {
//        
//        [self showToastWithText:@"货物数量不能为0"];
//        return;
//    }
//    
//    if (![parameters objectForKey:@"freightUnitPrice"]) {
//        
//        [self showToastWithText:@"请输入货物单价"];
//        return;
//    }
//    
//    if (0 == [[parameters objectForKey:@"freightUnitPrice"] integerValue]) {
//        
//        [self showToastWithText:@"货物单价不能为0"];
//        return;
//    }
    
    if ([[parameters objectForKey:@"demandModels"] length] == 0) {
        
        [self showToastWithText:@"请选择需求车型"];
        return;
    }
    
    if ([[parameters objectForKey:@"demandVehicleLength"] length] == 0) {
        
        [self showToastWithText:@"请选择需求车长"];
        return;
    }
    
    if ([[parameters objectForKey:@"loadingTime"] length] == 0) {
        
        [self showToastWithText:@"请选择装车时间"];
        return;
    }
    
    NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/buSources/1/save"];
    [GQHNetHelper qh_requestGET:URLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
        
        if (0 == [code intValue]) {
            GQHPushController *pushController = [[GQHPushController alloc] init];
            pushController.isGoods = YES;
            pushController.dataDic = data;
            [self.navigationController pushViewController:pushController animated:YES];
        } else {
            
            [self showToastWithText:message];
        }
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

#pragma mark --PrivateMethod
- (IBAction)datePickerChangeValue:(UIDatePicker *)sender {
    
    NSDate *date = sender.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    NSString *dateString = [formatter stringFromDate:date];
    UITextField *inputTextField = (UITextField *)[alertController.view viewWithTag:1011];
    inputTextField.text = dateString;
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
